define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'product_audit/index' + location.search,
                    detail_url: 'product_audit/detail',
                    audit_url: 'product_audit/audit',
                    edit_url: '', // 禁用编辑URL
                    del_url: '', // 禁用删除URL
                    table: 'product',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                // 禁用默认的编辑和删除操作
                commonSearch: false,
                showToggle: false,
                showColumns: false,
                columns: [
                    {checkbox: true},
                        {field: 'id', title: __('商品ID'), sortable: true, width: 80},
                        {field: 'name', title: __('商品名称'), operate: 'LIKE', width: 150},
                        {field: 'category.name', title: __('所属分类'), operate: false, width: 100},
                        {field: 'merchant_name', title: __('所属商家'), operate: false, width: 120},
                        {field: 'audit_status', title: __('商品审核状态'), searchList: {"2":__("待审核"), "1":__("审核通过"), "0":__("审核未通过")}, 
                            formatter: function(value, row, index) {
                                if (value == 2) {
                                    return '<span class="label label-warning">待审核</span>';
                                } else if (value == 1) {
                                    return '<span class="label label-success">审核通过</span>';
                                } else if (value == 0) {
                                    return '<span class="label label-danger">审核未通过</span>';
                                }
                                return value;
                            }, width: 120},
                        {field: 'createtime', title: __('提交时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, width: 120},
                        {field: 'audit_time', title: __('审核时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, width: 120},
                        {field: 'auditor', title: __('审核人'), operate: false, width: 80},
                        {field: 'operate', title: __('操作'), table: table, events: Table.api.events.operate, 
                            buttons: [
                                {
                                    name: 'detail',
                                    title: __('查看详情'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-list',
                                    url: 'product_audit/detail',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },
                                {
                                    name: 'approve',
                                    title: __('审核通过'),
                                    classname: 'btn btn-xs btn-success btn-approve-single',
                                    icon: 'fa fa-check',
                                    visible: function (row) {
                                        //只有待审核状态才显示审核通过按钮
                                        return row.audit_status == 2;
                                    }
                                },
                                {
                                    name: 'reject',
                                    title: __('审核拒绝'),
                                    classname: 'btn btn-xs btn-danger btn-reject-single',
                                    icon: 'fa fa-times',
                                    visible: function (row) {
                                        //只有待审核状态才显示审核拒绝按钮
                                        return row.audit_status == 2;
                                    }
                                },
                                {
                    name: 'reject_reason',
                    title: __('查看未通过原因'),
                    classname: 'btn btn-xs btn-warning btn-dialog',
                    icon: 'fa fa-exclamation-triangle',
                    url: 'product_audit/rejectReason',
                    visible: function (row) {
                        //只有审核未通过状态才显示查看原因按钮
                        return row.audit_status == 0;
                    }
                }
                            ],
                            formatter: Table.api.formatter.operate,
                            width: 200
                        }
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 批量审核通过
            $(document).on('click', '.btn-approve', function () {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.error(__('Please select at least one record'));
                    return false;
                }
                Layer.confirm(__('确认批量审核通过选中的商品吗？'), function (index) {
                    Backend.api.ajax({
                        url: "product_audit/approve",
                        data: {ids: ids}
                    }, function (data, ret) {
                        table.bootstrapTable('refresh');
                        Layer.close(index);
                    });
                });
            });

            // 批量审核拒绝
            $(document).on('click', '.btn-reject', function () {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.error(__('Please select at least one record'));
                    return false;
                }
                
                // 打开拒绝原因输入弹窗
                Layer.open({
                    type: 2,
                    title: __('批量审核拒绝'),
                    shadeClose: true,
                    shade: false,
                    maxmin: true,
                    area: ['500px', '300px'],
                    content: Fast.api.fixurl("product_audit/reject") + "?ids=" + ids.join(","),
                    yes: function (index, layero) {
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        var form = iframeWin.$("form");
                        form.data("validator-options", {
                            ignore: ':hidden',
                            validClass: 'has-success',
                            invalidClass: 'has-error',
                            bindClassTo: '.form-group',
                            formClass: 'n-default n-bootstrap',
                            msgClass: 'n-right',
                            callback: function (form) {
                                var data = form.serialize();
                                Backend.api.ajax({
                                    url: Fast.api.fixurl("product_audit/reject") + "?ids=" + ids.join(","),
                                    data: data
                                }, function (data, ret) {
                                    table.bootstrapTable('refresh');
                                    Layer.close(index);
                                });
                                return false;
                            }
                        });
                        form.validator("update").submit();
                        return false;
                    },
                    success: function (layero, index) {
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.Controller.api.bindevent();
                    }
                });
            });

            // 监听选择事件，控制批量操作按钮状态
            table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function () {
                var ids = Table.api.selectedids(table);
                $('.btn-approve, .btn-reject').toggleClass('disabled', ids.length === 0);
            });

            // 单个审核通过
            $(document).on('click', '.btn-approve-single', function () {
                var that = this;
                var $tr = $(that).closest('tr');
                var index = $tr.data('index');
                var row = table.bootstrapTable('getData')[index];
                
                if (!row || !row.id) {
                    Toastr.error(__('无法获取商品信息'));
                    return false;
                }
                
                Layer.confirm(__('确认审核通过该商品吗？'), function (layerIndex) {
                    Backend.api.ajax({
                        url: "product_audit/approve",
                        data: {ids: row.id}
                    }, function (data, ret) {
                        table.bootstrapTable('refresh');
                        Layer.close(layerIndex);
                    });
                });
            });
            
            // 单个审核拒绝
            $(document).on('click', '.btn-reject-single', function () {
                var that = this;
                var $tr = $(that).closest('tr');
                var index = $tr.data('index');
                var row = table.bootstrapTable('getData')[index];
                
                if (!row || !row.id) {
                    Toastr.error(__('无法获取商品信息'));
                    return false;
                }
                // 打开拒绝原因输入弹窗
                Layer.open({
                    type: 2,
                    title: __('审核拒绝'),
                    shadeClose: true,
                    shade: false,
                    maxmin: true,
                    area: ['500px', '300px'],
                    content: Fast.api.fixurl("product_audit/reject") + "?ids=" + row.id,
                    yes: function (index, layero) {
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        var form = iframeWin.$("form");
                        form.data("validator-options", {
                            ignore: ':hidden',
                            validClass: 'has-success',
                            invalidClass: 'has-error',
                            bindClassTo: '.form-group',
                            formClass: 'n-default n-bootstrap',
                            msgClass: 'n-right',
                            callback: function (form) {
                                var data = form.serialize();
                                Backend.api.ajax({
                                    url: Fast.api.fixurl("product_audit/reject") + "?ids=" + row.id,
                                    data: data
                                }, function (data, ret) {
                                    table.bootstrapTable('refresh');
                                    Layer.close(index);
                                });
                                return false;
                            }
                        });
                        form.validator("update").submit();
                        return false;
                    },
                    success: function (layero, index) {
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.Controller.api.bindevent();
                    }
                });
            });
        },
        detail: function () {
            Controller.api.bindevent();
        },
        audit: function () {
            Controller.api.bindevent();
        },
        reject: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});